package com.fer.controller;

import com.fer.mapper.BossManaMapper;
import com.fer.model.Boss;
import com.fer.model.State;
import com.fer.service.BossService;
import com.fer.service.impl.BossServiceImpl;
import com.fer.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/")
@Slf4j
public class BossController {
    @Autowired
    private BossServiceImpl bossService;
    @PostMapping("/login")
    //登录
    public Boss login(@RequestBody Boss boss, HttpServletRequest request, HttpServletResponse response){
        Boss user = bossService.login(boss);
        if(user==null){
            user = new Boss();
            user.setMessage("用户名或密码错误！");
            user.setCode(400);
        }
        else {
            user.setPassword("");
            user.setMessage("登录成功！");
            user.setCode(200);
            // 1、通过 session 来实现
//            每次登陆设置session
//            HttpSession session = request.getSession();
//            session.setAttribute("username", user.getUsername());
//            log.info("登录时候的sessionId：{}"+session.getId());
            // 2、通过 jwt 实现
            Map<String, String> map = new HashMap<>();
            // username
            map.put("username", boss.getUsername());
            // ip地址,防止这个token在其他ip地址使用
            map.put("ipAddress", request.getRemoteAddr());
            // 生成token
            String token = JWTUtils.getToken(map);
            // 将token放入cookie
            Cookie cookieToken = new Cookie("token", token);
            Cookie cookieUsername = new Cookie("username", boss.getUsername());
            //如果设置了htttonly的话，前端不能获取到cookie。
            // 防止脚本获取cookie
//            cookieToken.setHttpOnly(true);
//            cookieUsername.setHttpOnly(true);
            // 设置过期时间为7天
            cookieToken.setMaxAge(60*60*24*7);
            cookieUsername.setMaxAge(60*60*24*7);

            response.addCookie(cookieToken);
            response.addCookie(cookieUsername);
        }
        return user;
    }
    @PostMapping("/register")
    //注册
    public State register(@RequestBody Boss boss){
        State state = new State();
        try {
            String name = bossService.findUserByUsername(boss.getUsername());
            if(!(name==null || name.equals(""))) {
                state.setCode(400);
                state.setMessage("用户名已存在!");
                return state;
            }
            bossService.register(boss);
            state.setCode(200);
            state.setMessage("注册成功！");
        } catch (Exception e) {
            e.printStackTrace();
            state.setCode(400);
            state.setMessage("注册失败！");
        }
        return state;
    }
    @GetMapping("/findusername")
    //判断用户名
    public State findUsername(String username){
        String name = bossService.findUserByUsername(username);
        State state = new State();
        if(name==null || name.equals("")) {
            state.setCode(200);
            state.setMessage("用户名可用");
        }
        else{
            state.setCode(400);
            state.setMessage("用户名已存在!");
        }
        return state;
    }

    @GetMapping("/logout")
    //退出登录
    public State logout(HttpServletRequest request, HttpServletResponse response){
        // 1、session方式
//        HttpSession session = request.getSession();
//        session.removeAttribute("username");

        // 2、jwt实现
        // 清除两个cookie
        State state = new State();
        try {
            Cookie cookieToken = new Cookie("token", "");
            Cookie cookieUsername = new Cookie("username", "");

            cookieToken.setMaxAge(0);
            cookieUsername.setMaxAge(0);
            response.addCookie(cookieToken);
            response.addCookie(cookieUsername);
            log.info("清空cookie，退出登录");
            state.setCode(200);
            state.setMessage("退出登录成功！");
        } catch (Exception e) {
            state.setCode(500);
            state.setMessage("退出登录失败！");
            e.printStackTrace();
        }
        return state;
    }

    @PostMapping("/updatePassword")
    //修改密码
    public State updatePassword(@RequestBody Map<String, Object> user){
        Boss boss = new Boss();
        boss.setUsername((String) user.get("username"));
        boss.setPassword((String) user.get("password"));
        State state = new State();
        int status = bossService.updatePwd(boss, (String) user.get("newPassword"));
        if (status == -1){
            state.setMessage("原密码错误！");
            state.setCode(400);
        }else if(status==-2) {
            state.setMessage("服务器错误，修改失败！");
            state.setCode(500);
        }else {
            state.setMessage("修改成功！");
            state.setCode(200);
        }
        return state;
    }
}
